using Digitalmes.Domain.Entities.Mes.Reworks;

namespace Digitalmes.Application.Mes.Reworks.Doc.Queries;

/// <summary>
/// 产品返工单信息分页查询命令。
/// </summary>
public sealed record GetReworkDocListWithPagedQuery(
    string? Sn,
    string? ProductCode,
    DateTime? StartTime,
    DateTime? EndTime,
    int PageNumber,
    int PageSize) : IPagedQuery, IRequest<IResult<PagedList<ReworkDocDto>>>;

internal sealed class GetReworkDocListWithPagedQueryHandler(IRepository<ReworkDoc> repo) : IRequestHandler<GetReworkDocListWithPagedQuery, IResult<PagedList<ReworkDocDto>>>
{
    public async Task<IResult<PagedList<ReworkDocDto>>> Handle(GetReworkDocListWithPagedQuery request, CancellationToken cancellationToken)
    {
        var items = await repo.AsQueryable()
            .Includes(m => m.Defects)
            .WhereIF(!string.IsNullOrEmpty(request.Sn), m => m.Sn == request.Sn)
            .WhereIF(!string.IsNullOrEmpty(request.ProductCode), m => m.ProductCode == request.ProductCode)
            .WhereIF(request.StartTime.HasValue, m => m.StartTime >= request.StartTime.MinTime())
            .WhereIF(request.EndTime.HasValue, m => m.StartTime <= request.EndTime.MaxTime())
            .GetPagedListAsync(request.PageNumber, request.PageSize, cancellationToken);
        return Result.From(items.Adapt<PagedList<ReworkDocDto>>());
    }
}
